package com.glela.platform.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.glela.api.push.jpush.JPush;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.PushMessageMapper;
import com.glela.platform.model.PushMessage;
import com.glela.platform.model.request.RequestPushModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseMessageList;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.PushMessageService;

import cn.jpush.api.push.model.PushPayload;

/**
 * 
 * @author MaoZeYao
 *
 */
@Service("pushMessageService")
@Scope("singleton")
public class PushMessageServiceImpl implements PushMessageService {
	@Autowired
	private PushMessageMapper pushMessageMapper;
	
	@Override
	public void autoPushMessage(PushMessage pushMessage) {
		pushMessageMapper.insertIntoPushMessage(pushMessage);
		getPusMessageById(pushMessage.getId());
	}
	
	@Override
	public ResponseEntity<?> getPusMessageById(long id) {
		// TODO 自动生成的方法存根
		PushMessage push = pushMessageMapper.selectPushMessageById(id);
		// boolean apnsProduction = false; // 推送开发环境
		boolean apnsProduction = true; // 推送生产环境
		if (push == null) {
			// 没有这条数据
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22201), HttpStatus.OK);
		}
		if (push.getTitle() == null) {
			// 推送消息标题为空
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22202), HttpStatus.OK);
		}
		if (push.getContent() == null) {
			// 推送消息内容为空
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22203), HttpStatus.OK);
		}
		if (push.getStatus() == 2) {
			// 已经推送成功了
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22207), HttpStatus.OK);
		}
		JPush jpush = new JPush();
		jpush.setTitleAndContent(push.getTitle(), push.getContent());
		int status = -1 ;
		//推送为 个推
		if (push.getIsAll() == 0) {
			//没有指定到对应的接收人
			if (push.getUserId() ==  0) {
				// 个人推送，没有指定到对应的接收人
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22204), HttpStatus.OK);
			}
			//个人推送
			PushPayload payload = jpush.push_alias_alertWithTitle(push.getUserId()+"");
			payload.resetOptionsApnsProduction(apnsProduction);
			status = jpush.sendPush(payload) ;
		}else {
			//推送全部
			PushPayload payload = jpush.push_all_all_alertWithTitle();
			payload.resetOptionsApnsProduction(apnsProduction);
			status = jpush.sendPush(payload) ;
		}
		if (status == -1 ) {
			// 推送信息错误
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22205), HttpStatus.OK);
		}
		int updateStatus = pushMessageMapper.updatePushMessageSetStatus(id, status);
		if (updateStatus <= 0) {
			// 推送信息更新失败
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22206), HttpStatus.OK);
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C22200), HttpStatus.OK);
	}
	
	/**
	 * 消息详情
	 */
	@Override
	public ResponseEntity<?> getUserMessageByUserIdAndStatus(RequestPushModel model) {
		// TODO Auto-generated method stub
		List<PushMessage> pushList = pushMessageMapper.selectPushMessageByUserIdAndStatus(model.getUserId(),
				model.getType(), model.getStartIndex(), model.getPageSize());
		if(pushList.size() <= 0){
			List<PushMessage> nullList = new ArrayList<PushMessage>();
			return new ResponseEntity<>(new ResponseResultModel<>(nullList), HttpStatus.OK);
		}
		pushMessageMapper.updateNoReadMessage(model.getUserId(),model.getType());
		return new ResponseEntity<>(new ResponseResultModel<>(pushList), HttpStatus.OK);
	}

	/**
	 * 消息列表
	 */
	@Override
	public ResponseEntity<?> getUserMessageListByUserIdAndStatus(long userId) throws ParseException {
		//系统未读消息
		int sysNum = getUnreadMessageNums(userId, 0, 2);
		List<ResponseMessageList> resModel = new ArrayList<ResponseMessageList>();
		if (sysNum > 0) {
			PushMessage sysMsg = pushMessageMapper.selectPushMessageByUserIdAndTypeLimit(userId, 0);
			if (sysMsg != null) {
				ResponseMessageList sysModel = new ResponseMessageList();
				sysModel.setContent(sysMsg.getContent());
				sysModel.setType(sysMsg.getType());
				sysModel.setNoReadNum(sysNum);
				sysModel.setRecentlyTime(dealWithDate(sysMsg.getCreateTime()));
				resModel.add(sysModel);
			}
		}
		//钱包未读消息
		int moneyNum = getUnreadMessageNums(userId, 1, 2);
		if (moneyNum > 0) {
			PushMessage moneyMsg = pushMessageMapper.selectPushMessageByUserIdAndTypeLimit(userId, 1);
			if (moneyMsg != null) {
				ResponseMessageList moneyModel = new ResponseMessageList();
				moneyModel.setContent(moneyMsg.getContent());
				moneyModel.setType(moneyMsg.getType());
				moneyModel.setNoReadNum(moneyNum);
				moneyModel.setRecentlyTime(dealWithDate(moneyMsg.getCreateTime()));
				resModel.add(moneyModel);
			}
		}
		//物流未读消息
		int logisticsNum = getUnreadMessageNums(userId, 2, 2);
		if (logisticsNum > 0) {
			PushMessage logisticsMsg = pushMessageMapper.selectPushMessageByUserIdAndTypeLimit(userId, 2);
			if (logisticsMsg != null) {
				ResponseMessageList logisticsModel = new ResponseMessageList();
				logisticsModel.setContent(logisticsMsg.getContent());
				logisticsModel.setType(logisticsMsg.getType());
				logisticsModel.setNoReadNum(logisticsNum);
				logisticsModel.setRecentlyTime(dealWithDate(logisticsMsg.getCreateTime()));
				resModel.add(logisticsModel);
			}
		}
		return new ResponseEntity<>(new ResponseResultModel<>(resModel), HttpStatus.OK);
	}
	
	public String dealWithDate(String dateStr) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		SimpleDateFormat monthDay = new SimpleDateFormat("MM-dd");
		long createTime = sdf.parse(dateStr).getTime();
		long nowTime = new Date().getTime();
		long difference = nowTime - createTime;
		// 分钟
		long min = difference/1000/60;
		if(min < 60){
			return min+"分钟前";
		}
		//小时
		long hour = difference/1000/60/60;
		if(hour < 24){
			return hour+"小时前";
		}
		// 一周之内
		if(hour > 24 && hour/24 <= 7){
			String[] weekDaysName = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
			// String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(sdf.parse(dateStr));
			int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
			return weekDaysName[intWeek];
		}
		return monthDay.format(sdf.parse(dateStr));
	}

	@Override
	public int getUnreadMessageNums(Long userId, Integer type, Integer status) {
		return pushMessageMapper.selectNoReadMessage(userId, type, status, 0);
	}

}
